import json


from rest_framework.generics import CreateAPIView, RetrieveAPIView, ListAPIView
from rest_framework.response import Response
from rest_framework.views import APIView

from dingxiang_doctor.utils.myjwt import myjwt
from workflow.models import Workflow, WorkflowRole, WorkflowApprovalNode, Task
from myadmin.models import Admin
from workflow.serial import WorkflowSerializer, WorkflowApprovalNodeSerializer, TaskSerializer
from workflow.myagent import audit_workflow
from mycelery.all_task.task import send_email_to

# Create your views here.
# 新建工作流
class WorkflowCreateView(CreateAPIView):
    queryset = Workflow.objects.all()
    serializer_class = WorkflowSerializer

# 创建工作流对应角色
class WorkflowRoleCreateView(APIView):
    def post(self, request):
        workflow_id = request.data.get('workflow_id')
        role_list = request.data.get('role_list')
        workflow_role_list = []
        for role_id in role_list:
            workflow_role_list.append(WorkflowRole(workflow_id=workflow_id, role_id=role_id))
        WorkflowRole.objects.bulk_create(workflow_role_list)
        return Response({'message': '角色添加成功'})

# 获取某角色的工作流列表
class WorkflowListView(ListAPIView):
    serializer_class = WorkflowSerializer
    def get_queryset(self):
        token = self.request.headers.get("Authorization")
        data = myjwt.jwt_decode(token)
        role_id = data.get("data").get("role")
        workflow_id = WorkflowRole.objects.filter(role_id=role_id).values_list("workflow_id", flat=True)
        print("workflow_id:", workflow_id)
        workflow_list = Workflow.objects.filter(id__in=workflow_id)
        return workflow_list

# 获取某一工作流
class WorkflowRetrieveView(RetrieveAPIView):
    queryset = Workflow.objects.all()
    serializer_class = WorkflowSerializer

# 添加工作流审批
class WorkflowApprovalNodeCreateView(CreateAPIView):
    queryset = WorkflowApprovalNode.objects.all()
    serializer_class = WorkflowApprovalNodeSerializer

# 查看审批流程
class WorkflowApprovalNodeListView(APIView):
    def get(self, request):
        token = request.headers.get("Authorization")
        data = myjwt.jwt_decode(token)
        user_id = data.get("data").get("id")
        department_id = Admin.objects.get(id=user_id).department.id
        workflow_id = request.query_params.get('workflow_id')
        print("workflow_id:", workflow_id)
        print("department_id:", department_id)
        position_list = WorkflowApprovalNode.objects.filter(workflow_id=workflow_id).\
            values_list("position_id", flat=True)
        print(position_list)
        user_list = Admin.objects.filter(position_id__in=position_list, department=department_id).order_by("position")\
            .values_list("name", flat=True)
        print("user_list:", user_list)
        print("---------------------------")
        # send_email_to.delay("derek59117@163.com", "同意")
        # print("-----------------------------")
        return Response({"user_list": user_list})

# 调用Agent创建任务表
class TaskCreateView(APIView):
    def post(self, request):
        # 需要接收字段：name, params, workflow_id, admin, task_status
        token = request.headers.get("Authorization")
        admin = myjwt.jwt_decode(token).get("data").get("id")
        print(admin)
        message = request.data.get("message")
        print(message)
        message["name"] = message.get("params")[0].get("value") + "的出差申请"
        message["admin"] = admin
        message["task_status"] = 0
        the_message = json.dumps(message)
        data = audit_workflow(json.dumps({"title": "创建新任务", "message": the_message}))
        print("返回的任务id:", data["output"])
        response = data["output"]
        # 如果成功存入
        try:
            int(response)
            # 获取第一审批人
            response = audit_workflow(json.dumps({"title": "获取下一审批人", "message": data["output"]}))
            return Response({"code": 200, "response": response})
        except Exception:
            return Response({"code": 400, "response": response})

# 调用Agent获取下一审批人
class NextReviewerView(APIView):
    def post(self, request):
        # 需要接受字段：task_id, audit_user, audit_status, note
        token = request.headers.get("Authorization")
        admin = myjwt.jwt_decode(token).get("data").get("id")

        message = request.data.get("message")
        message["audit_user"] = admin

        # 将任务状态改为审核中
        task_id = message.get("task_id")
        task = Task.objects.get(id=task_id)
        task.task_status = 1
        task.save()

        # 填写审批表单
        data = audit_workflow(json.dumps({"title": "填写审批记录", "message": message}))

        # 本审批人审批通过
        if message.get("audit_status") == 1:
            flag = audit_workflow(json.dumps({"title": "获取下一审批人", "message": message.get("task_id")}))
        else:
            return Response({"response": "审批不通过"})
        return Response({"response": data})

# 获取审批人对应审批的任务表
class TaskListAPIView(ListAPIView):
    serializer_class = TaskSerializer
    def get_queryset(self):
        token = self.request.headers.get("Authorization")
        data = myjwt.jwt_decode(token)
        admin = data.get("data").get("id")
        queryset = Task.objects.filter(next_audit=admin).order_by("-create_time")
        return queryset

# 获取某个任务
class TaskRetrieveAPIView(RetrieveAPIView):
    queryset = Task.objects.all()
    serializer_class = TaskSerializer
